<template>
  <el-card class="trademark">
    <template #header>
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加</el-button>
    </template>

    <el-table :data="tmList" border class="mb-10">
      <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #default="{ row, $index }">
          <img :src="row.logoUrl" style="width: 80px;height: 80px;">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row, $index }">
          <el-button type="warning" :icon="Edit" @click="handleEdit(row, $index)">编辑</el-button>
          <el-button type="danger" :icon="Delete" @click="handleDelete(row, $index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page"
      v-model:page-size="limit"
      :total="total"
      :page-sizes="[3, 6, 9]"
      layout="prev, pager, next, jumper, -> ,sizes, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />


    <el-dialog
      v-model="dialogVisible"
      :title="tmForm.id?'修改品牌':'添加品牌'"
      width="50%"
      >
      
      <!-- :model="form" -->
      <el-form label-width="120px">
        <el-form-item label="品牌名称">
          <el-input v-model="tmForm.tmName"/>
        </el-form-item>
        <el-form-item label="品牌LOGO">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                上传图片必须是jpg且不能大于2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>


      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelSave">取消</el-button>
          <el-button type="primary" @click="onSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

  </el-card>
</template>

<script setup lang="ts">
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import { ref, onMounted, watch } from 'vue';
import trademarkApi, { type TrademarkModel, type TrademarkPageModel } from '@/api/trademark'
import { ElMessageBox, ElMessage, type UploadProps } from 'element-plus';
import { cloneDeep } from 'lodash'
const action = `${ import.meta.env.VITE_API_URL }/admin/product/upload`


const handleEdit = (row: TrademarkModel, $index: number) => {
    dialogVisible.value = true;
    tmForm.value = cloneDeep(row); // 这里需要深拷贝(深拷贝面试重点-单独说)
}
const handleDelete = (row: TrademarkModel, $index: number) => {
  ElMessageBox.confirm(
    `确认要删除[${ row.tmName }]吗?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    // 确认删除,调接口
    try {
      await trademarkApi.delete(row.id as number)
      ElMessage.success('删除成功')
      getPage() // 重新获取页面数据
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
  .catch(() => {})
}


// 新增
const dialogVisible = ref(false)
const showAddDialog = () => {
  dialogVisible.value = true;
}
const initTmForm = () => ({ // 函数是创建一个收集数据的对象
  tmName: '',
  logoUrl: ''
})
const tmForm = ref<TrademarkModel>(initTmForm()) // tmForm用来收集收集数据
// 取消保存
const cancelSave = () => {
  dialogVisible.value = false // 隐藏弹框
  tmForm.value = initTmForm(); // 重置表单
}
// 保存
const onSave = async () => {
  try {
    if (tmForm.value.id) {
      await trademarkApi.update(tmForm.value)
    } else {
      await trademarkApi.save(tmForm.value)
    }
    cancelSave(); // 隐藏弹框、重置表单
    getPage()// 重新获取数据
  } catch (error) {
    console.error(error)
    ElMessage.error('保存品牌失败,请重试')
  }
}


// 上传图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // response 是接口返回的数据
  // uploadFile 是上传文件的整个信息
  tmForm.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}


const page = ref(1)
const limit = ref(3);
// 每页条数改变的回调
const handleSizeChange = (val: number) => {
  // 组装数据
  limit.value = val
  // 发送请求
  getPage()
}
// 翻页的回调
const handleCurrentChange = (val: number) => {
  // 组装数据
  page.value = val
  // 发送请求
  getPage()
}


// 获取分页列表数据
const tmList = ref<TrademarkModel[]>([])
const total = ref(0)
const getPage = async () => {
  try {
    let result = await trademarkApi.getPage(page.value, limit.value)
    tmList.value = result.records; // 拿到展示的数据

    total.value = result.total; // 拿到总条数
  } catch (error) {
    ElMessage.error('获取品牌分页数据失败,请重试')
  }
}

onMounted(() => {
  getPage()
})

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>